package com.ksd.web.controller.system;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ksd.common.annotation.Log;
import com.ksd.common.config.PlayDataConfig;
import com.ksd.common.core.controller.BaseController;
import com.ksd.common.core.domain.AjaxResult;
import com.ksd.common.core.page.TableDataInfo;
import com.ksd.common.enums.BusinessType;
import com.ksd.common.utils.DateUtils;
import com.ksd.common.utils.StringUtils;
import com.ksd.common.utils.file.FileUploadUtils;
import com.ksd.common.utils.poi.ExcelUtil;
import com.ksd.quartz.util.JsonUtil;
import com.ksd.system.service.ISysOperLogService;
import com.ksd.web.controller.tool.UnzipUtility;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ksd.system.domain.SysVersion;
import com.ksd.system.service.ISysVersionService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 运营商列表Controller
 * 
 * @author y.wu
 * @date 2025-04-24
 */
@RestController
@RequestMapping("/system/sysVersion")
public class SysVersionController extends BaseController
{
    @Autowired
    private ISysVersionService sysVersionService;
    @Autowired
    private ISysOperLogService sysOperLogService;

    /**
     * 查询运营商列表列表
     */
    @PreAuthorize("@ss.hasPermi('system:sysVersion:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysVersion sysVersion)
    {
        startPage();
        List<SysVersion> list = sysVersionService.selectSysVersionList(sysVersion);
        return getDataTable(list);
    }

    /**
     * 导出运营商列表列表
     */
    @PreAuthorize("@ss.hasPermi('system:sysVersion:export')")
    @Log(title = "运营商列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysVersion sysVersion)
    {
        List<SysVersion> list = sysVersionService.selectSysVersionList(sysVersion);
        ExcelUtil<SysVersion> util = new ExcelUtil<SysVersion>(SysVersion.class);
        util.exportExcel(response, list, "运营商列表数据");
    }

    /**
     * 获取运营商列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sysVersion:query')")
    @GetMapping(value = {"/","/{id}"})
    public AjaxResult getInfo(@PathVariable(value = "id", required = false) Long id)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(id)){
            SysVersion sysVersion = sysVersionService.selectSysVersionById(id);
            ajax.put(AjaxResult.DATA_TAG, sysVersion);
        }
        List<SysVersion> sysVersions = sysVersionService.selectSysVersionList(new SysVersion());
        ajax.put("operators", sysVersions);
        return ajax;
    }

    /**
     * 新增运营商列表
     */
    @PreAuthorize("@ss.hasPermi('system:sysVersion:add')")
    @Log(title = "运营商列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysVersion sysVersion)
    {
        if (!sysVersionService.checkKeyUnique(sysVersion))
        {
            sysOperLogService.insertOperlogError("新增运营商'" + sysVersion.getOperatorName() + "'失败，该运营商标识已存在");
            return error("新增运营商'" + sysVersion.getOperatorName() + "'失败，该运营商标识已存在");
        }
        if (!sysVersionService.checkNameUnique(sysVersion))
        {
            sysOperLogService.insertOperlogError("新增运营商'" + sysVersion.getOperatorName() + "'失败，该运营商名称已存在");
            return error("新增运营商'" + sysVersion.getOperatorName() + "'失败，该运营商名称已存在");
        }
        sysOperLogService.insertOperlogSuccess("新增运营商成功,运营商名称:"+sysVersion.getOperatorName()+",运营商标识:"+sysVersion.getOperatorKey());
        return toAjax(sysVersionService.insertSysVersion(sysVersion));
    }

    @PostMapping("/uploadFile")
    public AjaxResult uploadApkZipFile(MultipartFile file, HttpServletRequest request) throws Exception
    {
        String operatorName = request.getParameter("operatorName");
        String operName = getUsername();
        System.out.println(operName+"=============上传文件:"+file.getSize()+"============"+operatorName);

        System.out.println("上传机顶盒升级文件,运营商名称:"+operatorName+"============="+file.getOriginalFilename());
        String importPath = PlayDataConfig.getUploadPath();
        String zipFilePath = FileUploadUtils.uploadName(importPath, file);
        System.out.println("压缩包上传到服务器的路径filePath:"+zipFilePath);

        String dataPath = File.separator+"playdata_apk_version"+File.separator+ DateUtils.dateTimeNow();
        String synchFilePath = PlayDataConfig.getSynchPath()+  dataPath; //服务器文件实际存储地址
        String mapperFilePath = PlayDataConfig.getMappedPath()+  dataPath; //服务器文件映射地址
        try {
            System.out.println("进行解压缩操作");
            UnzipUtility.unzip(zipFilePath,synchFilePath);
        } catch (IOException e) {
            System.out.println("解压缩出错:"+e.getMessage());
            sysOperLogService.insertOperlogError("上传机顶盒升级包失败,运营商:"+operatorName+",上传机顶盒版本压缩包解压失败.压缩包地址:"+zipFilePath);
            throw new RuntimeException(e);
        }
        System.out.println("解析上传机顶盒升级包");
        List<File> jsonFiles = JsonUtil.findJsonFiles(synchFilePath);
        System.out.println("jsonFiles size:"+jsonFiles.size());
        if (jsonFiles.size() > 0) {
            String jsonPath = jsonFiles.get(0).getAbsolutePath();
            System.out.println("jsonPath:"+jsonPath);
            SysVersion sysVersion = new SysVersion();
            sysVersion.setOperatorName(operatorName);
            sysVersion = sysVersionService.selectSysVersionList(sysVersion).get(0);
            //明确机顶盒升级包的地址
            List<File> apkFiles = UnzipUtility.findApkFiles(synchFilePath);
            if (apkFiles.size() > 0) {
                System.out.println("机顶盒版本:"+apkFiles.size());
                String apkUploadPath = apkFiles.get(0).getAbsolutePath();//机顶盒在云服务上的实际路径地址
                String apkName = apkFiles.get(0).getName();
                System.out.println("apkUploadPath:"+apkUploadPath+"================apkName:"+apkName);
                String endPath = apkUploadPath.substring(synchFilePath.length(), apkUploadPath.length());
                System.out.println("endPath:"+endPath);
                String apkMappedPath = mapperFilePath + File.separator+endPath; //通过nginx配置,能够通过浏览器直接访问到文件地址
                System.out.println("机顶盒升级包在云服务器上的实际文件地址apkUploadPath:"+apkUploadPath);
                System.out.println("机顶盒升级包的通过nginx配置指向的文件地址apkMappedPath:"+apkMappedPath);
                sysVersion.setUrl(PlayDataConfig.getCloudDownService() + apkMappedPath);//能够通过浏览器直接放到到
                sysVersion.setApkName(apkName);
                sysVersion.setDataFlag("0"); //初始化
                sysVersion.setStatus("0");
                sysVersion = UnzipUtility.readJsonFile(jsonPath, sysVersion);
                sysOperLogService.insertOperlogSuccess("上传机顶盒升级包成功,运营商:"+operatorName+"上传机顶盒版本:"+sysVersion.getVersion()+",升级包同步地址："+sysVersion.getUrl());
                sysVersionService.updateSysVersion(sysVersion);
            }else{
                sysOperLogService.insertOperlogError("上传机顶盒升级失败,运营商:"+operatorName+",上传机顶盒版本格式不对,未找到机顶盒升级版本");
                return AjaxResult.error("上传机顶盒版本格式不对,未找到机顶盒升级版本");
            }
        }else{
            sysOperLogService.insertOperlogError("上传机顶盒升级包成功,运营商:"+operatorName+",上传机顶盒版本格式不对,未找到机顶盒相关配置json文件");
            return AjaxResult.error("上传机顶盒版本格式不对,未找到机顶盒相关配置json文件");
        }

        return success("运营商:"+operatorName+",升级版本上传成功");
    }
    /**
     * 修改运营商列表
     */
    @PreAuthorize("@ss.hasPermi('system:sysVersion:edit')")
    @Log(title = "运营商列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysVersion sysVersion)
    {
        if (!sysVersionService.checkKeyUnique(sysVersion))
        {
            sysOperLogService.insertOperlogError("修改运营商'" + sysVersion.getOperatorName() + "'失败，该运营商标识已存在");
            return error("修改运营商'" + sysVersion.getOperatorName() + "'失败，该运营商标识已存在");
        }
        if (!sysVersionService.checkNameUnique(sysVersion))
        {
            sysOperLogService.insertOperlogError("修改运营商'" + sysVersion.getOperatorName() + "'失败，该运营商名称已存在");
            return error("修改运营商'" + sysVersion.getOperatorName() + "'失败，该运营商名称已存在");
        }
        sysOperLogService.insertOperlogSuccess("修改运营商成功,运营商名称:"+sysVersion.getOperatorName()+",运营商标识:"+sysVersion.getOperatorKey());
        return toAjax(sysVersionService.updateSysVersion(sysVersion));
    }

    /**
     * 删除运营商列表
     */
    @PreAuthorize("@ss.hasPermi('system:sysVersion:remove')")
    @Log(title = "运营商列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            SysVersion sysVersion = sysVersionService.selectSysVersionById(id);
            String url = sysVersion.getUrl();
            String synchPath = PlayDataConfig.getSynchPath();
            String mappedPath = PlayDataConfig.getMappedPath();
            String cloudDownService = PlayDataConfig.getCloudDownService();
            String substring = url.substring(cloudDownService.length() + mappedPath.length());
            System.out.println("substring:"+substring);
            String versionPath = synchPath+substring;
            System.out.println("versionPath:"+versionPath);
            File file = new File(versionPath);
            if (file.exists()) {
                boolean delete = file.delete();
                System.out.println("升级版本删除标识:"+delete);
            }
            sysVersionService.deleteSysVersionById(id);
            sysOperLogService.insertOperlogSuccess("删除运营商:"+sysVersion.getOperatorName()+" 成功.该运营商标识:"+sysVersion.getOperatorKey());
        }
        return success();
    }
}
